import indexObj from '../../unit/index.js';
import event from '../../unit/event';
import states from '../states';
import musicobj from '../../unit/music';
import Block from '../../unit/block.js';
let {
	want
} = indexObj;

let {
	music
} = musicobj;

const down = (store) => {
	store.commit("drop", true);
	event.down({
		key: 'space',
		once: true,
		callback: () => {
			const state = store.state;
			if (state.lock) {
				return;
			}
			const cur = state.cur;
			if (cur !== null) { // 置底
				if (state.pause) { //暂停的话就取消暂停
					states.pause(false);
					return;
				}
				if (music.fall) {
					music.fall();
				}
				let index = 0;
				let bottom = cur.fall(index);
				let matrix = state.matrix.map((m)=>{
					return m.slice();
				});
				while (want(bottom, matrix)) {
					bottom = cur.fall(index);
					index++;
				}

				bottom = cur.fall(index - 2);
				store.commit("moveBlock", bottom.reset === true ? null : new Block(bottom));
				const shape = bottom.shape;
				const xy = bottom.xy;
				shape.forEach((m, k1) => (
					m.forEach((n, k2) => {
						if (n && xy[0] + k1 >= 0) { // 竖坐标可以为负
							let line = matrix[xy[0] + k1];
							line[xy[1] + k2] = 1;
							matrix[xy[0] + k1] = line;
						}
					})
				));
				store.commit("drop", true);
				setTimeout(() => {
					store.commit("drop", false);
				}, 100);
				states.nextAround(matrix);
			} else {
				states.start();
			}
		},
	});
};

const up = (store) => {
	store.commit("drop", false);
	event.up({
		key: 'space',
	});
};

export default {
	down,
	up,
};
